package com.aiju.cash.util;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.aiju.app.SimpleHttpCallback;
import com.aiju.cash.core.api.HeartBeatApi;
import com.aiju.common.thread.AsyncExecutor;
import com.aiju.utils.L;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author: 佐为
 * @date: 2017-06-20 13:35
 * @version: V1.0
 * @Description: 描述
 */
public class PollingService extends Service {

    public static final String TAG = "heart";

    //执行次数
    private int count;
    //执行间隔
    private int period = 60 * 1000;

    private ScheduledExecutorService scheduledExecutor;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        L.d(TAG, "PollingService:onCreate");
        scheduledExecutor = AsyncExecutor.createScheduledExecutor();
        scheduledExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                L.d(TAG, "APP心跳" + count + "次");
                heartBeat(count);
                count++;
            }
        }, 0, period, TimeUnit.MILLISECONDS);
    }

    /**
     * 执行心跳
     */
    private void heartBeat(final int count) {
        new HeartBeatApi(null).heartBeat(new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                L.d(TAG, "服务器已接收第" + count + "心跳");
            }

            @Override
            protected void onDataFailure(int code, String msg) {
                super.onDataFailure(code, msg);
                L.d(TAG, "服务器接收第" + count + "心跳异常. " + msg);
            }
        });
    }

    @Override
    public void onStart(Intent intent, int startId) {
        L.d(TAG, "PollingService:onStart");
    }

    @Override
    public void onDestroy() {
        L.d(TAG, "PollingService:onDestroy");
        L.d(TAG, "APP心跳" + (count - 1) + "次后结束，登录时间：" + (count - 1) + "分钟");
        scheduledExecutor.shutdownNow();
        super.onDestroy();
    }

}
